<template>
  <div class="member-management">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="成员姓名">
          <el-input v-model="searchForm.name" placeholder="请输入成员姓名" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态">
            <el-option label="全部" value="" />
            <el-option label="待审核" value="pending" />
            <el-option label="已通过" value="approved" />
            <el-option label="已拒绝" value="rejected" />
          </el-select>
        </el-form-item>
        <el-form-item label="加入时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="success" @click="handleInvite">邀请成员</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table :data="memberList" border stripe>
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="姓名">
          <template #default="{ row }">
            <div class="member-info">
              <el-avatar :size="32" :src="row.avatar">{{ row.name ? row.name.substr(0, 1) : 'N/A' }}</el-avatar>
              <span>{{ row.name || row.username || '未设置姓名' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" width="120" />
        <el-table-column prop="email" label="邮箱" width="180" />
        <el-table-column prop="role" label="角色" width="100">
          <template #default="{ row }">
            <el-tag :type="getRoleType(row.role)">
              {{ getRoleText(row.role) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="joinTime" label="加入时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.joinTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="auditStatus" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.auditStatus)">
              {{ getStatusText(row.auditStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button 
              v-if="row.auditStatus === 0"
              link 
              type="primary" 
              @click="handleApprove(row)"
            >通过</el-button>
            <el-button 
              v-if="row.auditStatus === 0"
              link 
              type="danger" 
              @click="handleReject(row)"
            >拒绝</el-button>
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="primary" @click="handleDetail(row)">详情</el-button>
            <el-button link type="danger" @click="handleRemove(row)">移除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 邀请对话框 -->
    <el-dialog
      v-model="inviteDialogVisible"
      title="邀请成员"
      width="500px"
    >
      <el-form
        ref="inviteFormRef"
        :model="inviteForm"
        :rules="inviteRules"
        label-width="80px"
      >
        <el-form-item label="邀请方式">
          <el-radio-group v-model="inviteForm.type">
            <el-radio label="email">邮件邀请</el-radio>
            <el-radio label="link">链接邀请</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="inviteForm.type === 'email'"
          label="邮箱"
          prop="emails"
        >
          <el-input
            v-model="inviteForm.emails"
            type="textarea"
            :rows="3"
            placeholder="请输入邮箱地址，多个邮箱请用逗号或换行分隔"
          />
        </el-form-item>
        <el-form-item
          v-if="inviteForm.type === 'link'"
          label="邀请链接"
        >
          <el-input
            v-model="inviteLink"
            readonly
          >
            <template #append>
              <el-button @click="copyLink">复制</el-button>
            </template>
          </el-input>
          <div class="link-tip">链接有效期24小时</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="inviteDialogVisible = false">取消</el-button>
          <el-button
            v-if="inviteForm.type === 'email'"
            type="primary"
            @click="handleInviteSubmit"
          >发送邀请</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑成员"
      width="500px"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="80px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editForm.name" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="editForm.role">
            <el-option label="管理员" :value="0" />
            <el-option label="志愿者" :value="1" />
            <el-option label="普通成员" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input
            v-model="editForm.remarks"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleEditSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="成员详情"
      width="600px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="头像" :span="2">
          <el-avatar :size="64" :src="currentDetail.avatar">
            {{ currentDetail.name ? currentDetail.name.substr(0, 1) : 'N/A' }}
          </el-avatar>
        </el-descriptions-item>
        <el-descriptions-item label="姓名">{{ currentDetail.name || '未设置' }}</el-descriptions-item>
        <el-descriptions-item label="用户名">{{ currentDetail.username || '未设置' }}</el-descriptions-item>
        <el-descriptions-item label="角色">
          <el-tag :type="getRoleType(currentDetail.role)">
            {{ getRoleText(currentDetail.role) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="用户ID">{{ currentDetail.userId }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ currentDetail.phone || '未设置' }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ currentDetail.email || '未设置' }}</el-descriptions-item>
        <el-descriptions-item label="加入时间">{{ formatDate(currentDetail.joinTime) }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(currentDetail.auditStatus)">
            {{ getStatusText(currentDetail.auditStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item v-if="currentDetail.rejectReason" label="拒绝原因" :span="2">
          {{ currentDetail.rejectReason }}
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getMemberList,
  getMemberDetail,
  addMember,
  updateMember,
  removeMember,
  approveMember,
  rejectMember,
  sendInvitation,
  getInviteLink
} from '@/api/member'

// 搜索表单
const searchForm = reactive({
  name: '',
  status: '',
  dateRange: []
})

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 成员列表
const memberList = ref([])

// 邀请对话框
const inviteDialogVisible = ref(false)
const inviteFormRef = ref(null)
const inviteForm = reactive({
  type: 'email',
  emails: ''
})
const inviteLink = ref('')
const inviteRules = {
  emails: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' }
  ]
}

// 编辑对话框
const editDialogVisible = ref(false)
const editFormRef = ref(null)
const editForm = reactive({
  id: '',
  name: '',
  role: '',
  remarks: ''
})
const editRules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 详情对话框
const detailDialogVisible = ref(false)
const currentDetail = ref({})

// 初始化加载数据
onMounted(() => {
  fetchMemberList()
})

// 获取成员列表数据
const fetchMemberList = async () => {
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      name: searchForm.name || undefined,
      status: searchForm.status || undefined
    }
    
    // 处理日期范围
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.startDate = searchForm.dateRange[0]
      params.endDate = searchForm.dateRange[1]
    }
    
    const res = await getMemberList(params)
    memberList.value = res.data.list || []
    total.value = res.data.total || 0
  } catch (error) {
    console.error('获取成员列表失败', error)
  }
}

// 日期格式化函数
const formatDate = (dateString) => {
  if (!dateString) return '暂无';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  }).replace(/\//g, '-');
}

// 获取角色类型
const getRoleType = (role) => {
  const types = {
    0: 'danger',   // 管理员
    1: 'primary',  // 志愿者
    2: '',         // 普通成员
    admin: 'danger',
    member: ''
  }
  return types[role] || ''
}

// 获取角色文本
const getRoleText = (role) => {
  const texts = {
    0: '管理员',
    1: '志愿者',
    2: '普通成员',
    admin: '管理员',
    member: '普通成员'
  }
  return texts[role] || '未知'
}

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    0: 'warning',  // 待审核
    1: 'success',  // 已通过
    2: 'danger',   // 已拒绝
    pending: 'warning',
    approved: 'success',
    rejected: 'danger'
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    0: '待审核',
    1: '已通过',
    2: '已拒绝',
    pending: '待审核',
    approved: '已通过',
    rejected: '已拒绝'
  }
  return texts[status] || '未知'
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchMemberList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = key === 'dateRange' ? [] : ''
  })
  currentPage.value = 1
  fetchMemberList()
}

// 处理邀请
const handleInvite = async () => {
  inviteDialogVisible.value = true
  inviteForm.type = 'email'
  inviteForm.emails = ''
  
  if (inviteForm.type === 'link') {
    try {
      const res = await getInviteLink()
      inviteLink.value = res.data.link
    } catch (error) {
      console.error('获取邀请链接失败', error)
      ElMessage.error('获取邀请链接失败')
    }
  }
}

// 复制链接
const copyLink = () => {
  navigator.clipboard.writeText(inviteLink.value)
  ElMessage.success('链接已复制')
}

// 处理邀请提交
const handleInviteSubmit = async () => {
  if (!inviteFormRef.value) return
  
  await inviteFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 处理邮箱列表
        const emails = inviteForm.emails
          .split(/[,，\n]/)
          .map(email => email.trim())
          .filter(email => email)
        
        await sendInvitation({ emails })
        ElMessage.success('邀请已发送')
        inviteDialogVisible.value = false
      } catch (error) {
        console.error('发送邀请失败', error)
        ElMessage.error('发送邀请失败')
      }
    }
  })
}

// 处理审核通过
const handleApprove = (row) => {
  ElMessageBox.confirm(
    '确认通过该成员的申请？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await approveMember(row.id)
      ElMessage.success('已通过该成员的申请')
      fetchMemberList()
    } catch (error) {
      console.error('审核失败', error)
      ElMessage.error('审核失败')
    }
  })
}

// 处理审核拒绝
const handleReject = (row) => {
  ElMessageBox.prompt('请输入拒绝原因', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputType: 'textarea',
    inputPlaceholder: '请输入拒绝原因'
  }).then(async ({ value }) => {
    try {
      await rejectMember(row.id, value)
      ElMessage.success('已拒绝该成员的申请')
      fetchMemberList()
    } catch (error) {
      console.error('拒绝失败', error)
      ElMessage.error('拒绝失败')
    }
  })
}

// 处理编辑
const handleEdit = async (row) => {
  try {
    const res = await getMemberDetail(row.id)
    const data = res.data
    
    editForm.id = data.id
    editForm.name = data.name || ''
    editForm.role = data.role
    
    // 备注可能不在后端返回数据中，确保不报错
    editForm.remarks = data.remarks || ''
    
    editDialogVisible.value = true
  } catch (error) {
    console.error('获取成员详情失败', error)
    ElMessage.error('获取成员详情失败')
  }
}

// 处理编辑提交
const handleEditSubmit = async () => {
  if (!editFormRef.value) return
  
  await editFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 确保role是数字类型
        const roleValue = Number.isInteger(editForm.role) ? editForm.role : parseInt(editForm.role, 10)
        
        await updateMember(editForm.id, {
          name: editForm.name,
          role: roleValue,
          remarks: editForm.remarks
        })
        
        ElMessage.success('更新成功')
        editDialogVisible.value = false
        fetchMemberList()
      } catch (error) {
        console.error('更新失败', error)
        ElMessage.error('更新失败')
      }
    }
  })
}

// 查看详情
const handleDetail = async (row) => {
  try {
    const res = await getMemberDetail(row.id)
    currentDetail.value = res.data
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取成员详情失败', error)
    ElMessage.error('获取成员详情失败')
  }
}

// 处理移除
const handleRemove = (row) => {
  ElMessageBox.confirm(
    '确认移除该成员？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await removeMember(row.id)
      ElMessage.success('已移除该成员')
      fetchMemberList()
    } catch (error) {
      console.error('移除失败', error)
      ElMessage.error('移除失败')
    }
  })
}

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchMemberList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchMemberList()
}
</script>

<style scoped lang="scss">
.member-management {
  .search-card {
    margin-bottom: 20px;
  }

  .table-card {
    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .link-tip {
    margin-top: 8px;
    color: #909399;
    font-size: 12px;
  }
  
  .member-info {
    display: flex;
    align-items: center;
    gap: 10px;
    
    .el-avatar {
      flex-shrink: 0;
    }
    
    span {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}
</style> 